package com.authine.cloudpivot.ext.controller.workflow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.authine.cloudpivot.ext.service.IZzdWorkApiService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 浙政钉待办相关操作接口
 *
 * @author shinka
 */
@Api(value = "浙政钉待办相关操作接口", tags = "01::EXTAPI::浙政钉待办相关操作接口")
@RestController
@RequestMapping("/public/ext/zzd2")
public class ZzdWorkItem2Controller extends BaseController {

    private static Logger log = LoggerFactory.getLogger(ZzdWorkItem2Controller.class);

    // @Autowired
    // private DubboConfigService dubboConfigService;

    @Autowired
    private IZzdWorkApiService zzdWorkApi;

    @SuppressWarnings("unchecked")
    @ApiOperation(value = "查询浙政钉我的待办")
    @ApiImplicitParam(name = "userId", value = "浙政钉用户ID（云枢系统用户账号）", dataType = "String", paramType = "query")
    @PostMapping({"/queryWorkitem"})
    public ResponseResult<JSONObject> queryWorkitem(@RequestParam String userId) {
        log.info(" queryWorkitem userId = {}", userId);
        try {
            int pageNo = 1;
            int pageSize = 5;
            int count = 0;
            int totalSize = 0;
            List<JSONObject> workItemList = new ArrayList<>();
            boolean flag = true;
            while (flag) {
                Map<String, String> params = new HashMap<>();
                params.put("userId", String.valueOf(userId));
                params.put("pageNo", String.valueOf(pageNo));
                params.put("pageSize", String.valueOf(pageSize));
                String apiResult = zzdWorkApi.getTodoList(params);
                JSONObject json = JSONObject.fromObject(apiResult);
                if (json.getBoolean("success")) {
                    JSONObject content = json.getJSONObject("content");
                    JSONArray data = content.getJSONArray("data");
                    if (totalSize == 0) {
                        totalSize = content.getInt("totalSize");
                    }
                    workItemList.addAll(data);
                    // 是否需要继续查询
                    count += pageSize;
                    int s = totalSize - count;
                    if (s < 0 || s == 0) {
                        flag = false;
                    }
                    pageNo += 1;
                }
            }
            List<Object> taskUuidList = new ArrayList<>();
            for (JSONObject o : workItemList) {
                taskUuidList.add(o.get("taskUuid"));
            }
            // String taskUuidListStr =
            // taskUuidList.toString().toString().replace("[", "").replace("]", "").replaceAll("\"", "");
            JSONObject resultJson = new JSONObject();
            resultJson.put("workItemList", workItemList);
            resultJson.put("taskUuidList", taskUuidList);
            return getOkResponseResult(resultJson, "查询浙政钉我的待办成功");
        } catch (Exception e) {
            return getErrResponseResult(null, null, "查询浙政钉我的待办失败：" + e.toString());
        }
    }

    @ApiOperation(value = "取消浙政钉我的待办")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "userId", value = "浙政钉用户ID（云枢系统用户账号）", dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "taskUuidList", value = "任务唯一ID，由查询待办接口返回。多个值之间英文逗号分割，形如：aaa,bbb,ccc",
            dataType = "List", paramType = "body")})
    @PostMapping({"/cancelWorkitem"})
    public ResponseResult<Object> cancelWorkitem(@RequestParam String userId, @RequestBody List<String> taskUuidList) {
        log.info(" cancelWorkitem userId={},taskUuid={}", userId, taskUuidList);
        try {
            JSONObject resultJson = new JSONObject();
            for (String taskUuid : taskUuidList) {
                taskUuid = taskUuid.trim();
                Map<String, String> params = new HashMap<>();
                params.put("closePackage", "true");
                params.put("userId", userId);
                params.put("taskUuid", taskUuid);
                String apiResult = zzdWorkApi.taskCancel(params);
                resultJson.put(taskUuid, JSONObject.fromObject(apiResult));
            }
            return getOkResponseResult(resultJson, "取消浙政钉我的待办成功");
        } catch (Exception e) {
            return getErrResponseResult(null, null, "取消浙政钉我的待办失败：" + e.toString());
        }
    }
}
